<template>
    <div class="stopwatch">
      <div class="display">{{ formattedTime }}</div>
      <div class="controls">
        <button 
          v-if="!isRunning" 
          @click="start"
          :disabled="isRunning"
        >
          {{ elapsedTime === 0 ? '开始' : '继续' }}
        </button>
        <button 
          v-else 
          @click="pause"
        >
          暂停
        </button>
        <button 
          @click="reset"
          :disabled="elapsedTime === 0"
        >
          重置
        </button>
      </div>
      <div class="status">状态：{{ statusText }}</div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onBeforeUnmount } from 'vue'
  
  const elapsedTime = ref(0) // 毫秒数
  const isRunning = ref(false)
  let startTime = 0
  let intervalId: number | null = null
  
  const formattedTime = computed(() => {
    const date = new Date(elapsedTime.value)
    const hours = date.getUTCHours().toString().padStart(2, '0')
    const minutes = date.getUTCMinutes().toString().padStart(2, '0')
    const seconds = date.getUTCSeconds().toString().padStart(2, '0')
    const milliseconds = Math.floor(date.getUTCMilliseconds() / 10)
      .toString()
      .padStart(2, '0')
    return `${hours}:${minutes}:${seconds}.${milliseconds}`
  })
  
  const statusText = computed(() => {
    if (elapsedTime.value === 0) return '准备就绪'
    return isRunning.value ? '运行中...' : '已暂停'
  })
  
  function start() {
    if (isRunning.value) return
    
    isRunning.value = true
    startTime = Date.now() - elapsedTime.value
    intervalId = window.setInterval(() => {
      elapsedTime.value = Date.now() - startTime
    }, 10)
  }
  
  function pause() {
    if (!isRunning.value) return
    
    isRunning.value = false
    if (intervalId) {
      clearInterval(intervalId)
      intervalId = null
    }
  }
  
  function reset() {
    pause()
    elapsedTime.value = 0
  }
  
  onBeforeUnmount(() => {
    if (intervalId) {
      clearInterval(intervalId)
    }
  })
  </script>
  
  <style scoped>
  .stopwatch {
    text-align: center;
    max-width: 400px;
    margin: 2rem auto;
    padding: 20px;
    border: 1px solid #eee;
    border-radius: 8px;
  }
  
  .display {
    font-size: 2.5em;
    font-family: monospace;
    margin: 20px 0;
    color: #333;
  }
  
  .controls button {
    font-size: 1.1em;
    margin: 0 5px;
    padding: 8px 16px;
    cursor: pointer;
    background: #f0f0f0;
    border: 1px solid #ddd;
    border-radius: 4px;
    transition: all 0.2s;
  }
  
  .controls button:hover {
    background: #e0e0e0;
  }
  
  .controls button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
  
  .status {
    margin-top: 15px;
    color: #666;
  }
  </style>